using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TitanX;
using System;
using DG.Tweening;
using UnityEditor;

public class DiceManger : SingletonGetMono<DiceManger>
{

    //初始的点位
    private Vector3 initPostion;
    //初始的父级点位
    private Vector3 initParentPostion;
    //初始的影子点位
    private Vector3 initShadowPostion;
    //初始的影子大小
    private Vector3 shadowInitScale;
    //影子
    public GameObject shadow;
    //骰子的点位图
    public Sprite[] sprites;
    public Sprite[] handleSprites;

    public GameObject handle;


    //筛子的类型
    public enum DiceType{
        action,card
    }


    public bool isMove;
    private Animator animator;
    private AnimatorStateInfo animatorInfo;
    public float animatorInfoTime;
    public bool isRoll;
        // Start is called before the first frame update
    void Start()
    {       
        //记下初始的点位
        initPostion = gameObject.transform.position;
        initParentPostion = gameObject.transform.parent.position;
        initShadowPostion = shadow.transform.position;


        shadowInitScale= shadow.transform.localScale;
        animator = transform.GetComponent<Animator>();
        animator.speed = 0f;
    }

    //开始抛物线
    public void StartPwx() {


        handle.GetComponent<SpriteRenderer>().sprite = handleSprites[1];
        handle.GetComponent<SpriteRenderer>().DOFade(0, 0.3f);


        distanceToTarget = Vector3.Distance(this.transform.position, target.transform.position);
        animator.SetBool("isRoll", true);
        IsMove = true;
        //开始抛物线移动轨迹
        StartCoroutine(StartShoot());
        animator.speed = 1f;
    }


    // Update is called once per frame
    void Update()
        {


        if (isMove)
        {
            //shadow.transform.position = new Vector3(transform.position.x, shadow.transform.position.y, shadow.transform.position.z);
            //影子缩小
            //要随着，y轴的增大而缩小

             handle.transform.position = transform.position;
            handle.GetComponent<SpriteRenderer>().DOFade(1, 0.3f);


            float y = transform.position.y;
            Vector3 v3 = new Vector3(transform.position.y * 0.005f, transform.position.y * 0.005f, 0);
            shadow.transform.localScale = shadowInitScale - v3;
            shadow.transform.position = new Vector3(transform.position.x, shadow.transform.position.y, shadow.transform.position.z);
        }
      

        if (isRoll) {

            //在一个点，改变点数
            int v = UnityEngine.Random.Range(3, 5);

          
            animator.SetBool("isRoll", false);

       
           // animator.enabled = false;
           // transform.parent.GetComponent<Animator>().enabled = false;
            transform.parent.GetComponent<Animator>().speed = 0;
            gameObject.GetComponent<SpriteRenderer>().sprite = sprites[v];


            //结束掷骰子--过程
            transform.DOMoveY(transform.position.y+0.8f, 0.8f).OnComplete(delegate {

                
                //隐藏骰子和影子
               transform.GetComponent<SpriteRenderer>().DOFade(0, 0.6f);
               shadow.transform.GetComponent<SpriteRenderer>().DOFade(0, 0.6f).OnComplete(delegate {


                   StopCoroutine(StartShoot());
                   //还原初始点位
                   transform.parent.position = initParentPostion;
                   transform.position = initPostion;
                   shadow.transform.position = initShadowPostion;


               });

             
                //设置影子大小为0
              
            });


   
            //调用一个方法，告诉你可以随机了
            GameManger.Instance.RollAfter (v);
            //  gameObject.SetActive(false);
          //  AnimationClipSettings clipSetting = AnimationUtility.GetAnimationClipSettings(animator.getAni());
            isRoll = false;
          
        }


    }


      



            



        //掷骰子
        public int Roll() {
       

        //播放指定的动画，等待返回结果

        //  gameObject.transform.position = initPostion;
        //   animator.se


        //翻卡

        //    gameObject.SetActive(true);

             isRoll = true;
                //当前动画状态所在的层
            //当前片段的播放进度[0,1] 0为起点 1为终点
            return 0;
       
        }



    public void reSet() {
        //transform.parent.GetComponent<Animator>().enabled = true;
        transform.parent.GetComponent<Animator>().speed = 1;

       // animator.Play("hit", 0, 0f);

        transform.parent.GetComponent<Animator>().Play("假的-骰子", 0, 0f);
        transform.parent.gameObject.SetActive(true);

        transform.GetComponent<SpriteRenderer>().DOFade(1, 0.1f);
        shadow.transform.GetComponent<SpriteRenderer>().DOFade(1, 0.1f);



    }




    public GameObject target;   //要到达的目标
    public float speed = 10;    //速度
    private float distanceToTarget;   //两者之间的距离
    private bool IsMove = true; //判断是否到达位置
/*

    //如果有拖尾效果，延迟一定时间再显示，否则尾巴会有残影
    IEnumerator Move(Vector3 startPos, Vector3 endPos, float centerOffset, float time = 0.5f, Action onComplete = null)
    {
        TrailRenderer trail = gameObject.GetComponentInChildren<TrailRenderer>(true);
        yield return new WaitForSeconds(trail ? trail.time : 0);
        //如果路径点较少，可以使用CatmullRom曲线插值类型运动，默认PathType.Linear
        //同时可以设置easetype来使用不同的运动方式，其它easetype:https://blog.csdn.net/w0100746363/article/details/83587485
        //如果想让物体一直朝着路径方向可以加上SetLookAt(0):DOPath(path, time).SetLookAt(0);
        Tween tween = gameObject.transform.DOPath(Path(startPos, endPos, centerOffset, 6), time, PathType.CatmullRom);
        ·

        if (onComplete != null)
        {
            shadow.transform.position = new Vector3(transform.position.x, transform.position.y, 0);

            tween.OnComplete(new DG.Tweening.TweenCallback(onComplete));
        }
        if (trail)
            trail.enabled = true;
    }


    //构建一个路径点
    private Vector3[] Path(Vector3 startTrans, Vector3 endTrans, float centerCtl, int segmentNum)
    {
        var startPoint = startTrans;
        var endPoint = endTrans;
        //中间点：起点和终点的向量相加再乘一个系数，系数可以根据实际调整
        var bezierControlPoint = (startPoint + endPoint) * centerCtl;
 
        //segmentNum为int类型，路径点数量，值越大，路径点越多，曲线越平滑 贝塞尔曲线
        Vector3[] path = new Vector3[segmentNum];
        for (int i = 0; i < segmentNum; i++)
        {
            var time = (i + 1) / (float)segmentNum;//归化到0~1范围
            path[i] = GetBezierPoint(time, startPoint, bezierControlPoint, endPoint);//使用贝塞尔曲线的公式取得t时的路径点
        }
        return path;
    }




    /// <param name="t">0到1的值，0获取曲线的起点，1获得曲线的终点</param>
    /// <param name="start">曲线的起始位置</param>
    /// <param name="center">决定曲线形状的控制点</param>
    /// <param name="end">曲线的终点</param>
    private Vector3 GetBezierPoint(float t, Vector3 start, Vector3 center, Vector3 end)
    {
        return (1 - t) * (1 - t) * start + 2 * t * (1 - t) * center + t * t * end;
    }
    */

    IEnumerator StartShoot()
    {
        while (IsMove)
        {

           

            Vector3 targetPos = target.transform.position;
            //让始终它朝着目标
            this.transform.LookAt(targetPos);
            //计算弧线中的夹角
            float angle = Mathf.Min(1, Vector3.Distance(this.transform.position, targetPos) / distanceToTarget) * 45;
            //获取角度
            this.transform.rotation = this.transform.rotation * Quaternion.Euler(Mathf.Clamp(-angle, -42, 42), 0, 0);
            //获取距离
            float currentDist = Vector3.Distance(this.transform.position, target.transform.position);
            shadow.transform.position = new Vector3(transform.position.x, transform.position.y-2.83f, shadow.transform.position.z);
            

                    //    shadow.transform.position = new Vector3(transform.position.x, transform.position.y , shadow.transform.position.z);

                       // Vector3 v3 = new Vector3(transform.position.y * 0.01f, transform.position.y * 0.01f, 0);
                      // shadow.transform.localScale = shadowInitScale - v3;
            
            //判断距离是否达到，达到后，停止移动
            if (currentDist < 0.5f) {

                Roll();
                IsMove = false;
                //调用世界n
                   //开始接下来的程序
            }
            this.transform.Translate(Vector3.forward * Mathf.Min(speed * Time.deltaTime, currentDist));
           
            
            yield return null;
        }




    }





public void updatePwxLine(){


//Path(startPos, endPos, centerOffset, 6);




}



//绘制带发射线

public GameObject lineGM;

    IEnumerator PwxLine(Vector3 startPos)
    {
            float offsetTime=1.5f;


        while (IsMove)
        {



            

            Vector3 targetPos = target.transform.position;
            //让始终它朝着目标
            lineGM.transform.LookAt(targetPos);
            //计算弧线中的夹角
            float angle = Mathf.Min(1, Vector3.Distance(lineGM.transform.position, targetPos) / distanceToTarget) * 45;
            //获取角度
            lineGM.transform.rotation = lineGM.transform.rotation * Quaternion.Euler(Mathf.Clamp(-angle, -42, 42), 0, 0);
            //获取距离
            float currentDist = Vector3.Distance(lineGM.transform.position, target.transform.position);

            if(currentDist%offsetTime==0){

                    //从对象池取出一个物体，生成一下

                    
            }       

            //每隔 一定的距离，生成一个球体
        //    shadow.transform.position = new Vector3(transform.position.x, transform.position.y-2.83f, shadow.transform.position.z);
            

       
            
            //判断距离是否达到，达到后，停止移动
            if (currentDist < 0.2f) {
                //重新发射
                //回到原始点
                lineGM.transform.position = this.transform.position;
                  }
            lineGM.transform.Translate(Vector3.forward * Mathf.Min(speed * Time.deltaTime, currentDist));
           
            
            yield return null;
        }




    }

}
